 //
//  advertView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/25.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AdvertView: BaseView, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate, DefinTimeDelegate, SlecterProcotol{
    var viewModel:AdvertViewViewModel?
    var selectView:UIView?

    var securitySwitch:UISwitch?
    var trustSwitch:UISwitch?
    
    var priceTextField:BaseTextField? //价格
    var smallAmount:BaseTextField? //最小量
    var bigAmount:BaseTextField? //最大量
    var termTextField:BaseTextField? //期限
    var lowerTextField:BaseTextField? //出售最低价
    
    var buyAddTag:Int = 0
    
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
    lazy var footView:UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 235))
        return view
    }()
    lazy var textView:BaseTextView = {
       let textView = BaseTextView(changeView: tableView)
       textView.themeBackground = ThemeManager.ThemeColorKeys.background
       textView.delegate = self
       return textView
    }()
    lazy var placeHolderLabel:UILabel = {
        let label = BaseLabel(style: .thirdStyle)
        label.text = kText("广告留言（下单前后都可见）\n请说明有关您交易的相关条款。")
        label.numberOfLines = 0
        label.sizeToFit()
        
        return label
    }()
    
   
    override func setUpUI() -> Void {
        
        viewModel = dataSource as? AdvertViewViewModel
        //注册监听
        viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        
        buyAddTag = (viewModel?.isBuyBool)! ? 0 : 1
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
//        UIScrollViewKeyboardDismissModeOnDrag
        tableView.delegate = self
        tableView.dataSource = self
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }

    }
    
    
    //MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (viewModel?.cellfactory.iteamArray[section].count)!
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return (viewModel?.cellfactory.iteamArray.count)!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = viewModel?.cellfactory.itemAtIndexPath(indexPath)
        let cellIdentifier = viewModel?.cellfactory.cellIdentiferAtIndexPath(indexPath)
        switch item?.type! {
        case .cyadvertSelectType?:
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? AdverSelectCell
            if cell == nil {
                cell = AdverSelectCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.textField.placeholder = item?.placeHolder
                cell?.indexPath = indexPath
                cell?.setAdverStyle()
                cell?.selectionStyle = .none
                if indexPath.section == 0 && indexPath.row == 2 {
                    cell?.line.isHidden = true
                }else {
                    cell?.line.isHidden = false
                }
                
                cell?.textField.delegate = self
                cell?.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
                
                cell?.tipBlock = {[weak self] (indexPath:IndexPath) in
                    if let vc = self?.dataSource.controller {
                        let item:CYAdvertItem = self?.viewModel?.cellfactory.iteamArray[indexPath.section][indexPath.row] as! CYAdvertItem
                        Alert.default.show(title: kText("提示"), message: item.prompt, actions: [kText("确定")], from: vc)
                    }
                }

                
            }
            cell?.setItem(item: item as! CYAdvertItem)
            cell?.textField.isUserInteractionEnabled = true
            if indexPath.section == 0 {
                cell?.kindLabel.isHidden = true
                switch indexPath.row {
                case 0:
                    cell?.inforLabel.text = viewModel?.coninKid.count != 0 ? viewModel?.coninKid : item?.placeHolder
                    cell?.changeColor(isHaveContent: viewModel?.coninKid.count != 0 ? true : false)
                    
                    break
                case 1:
                    cell?.inforLabel.text = viewModel?.countryStr.count != 0 ? viewModel?.countryStr : item?.placeHolder
                    cell?.changeColor(isHaveContent: viewModel?.countryStr.count != 0 ? true : false)
                    
                    break
                case 2:
                    cell?.inforLabel.text = viewModel?.legalCoin.count != 0 ? viewModel?.legalCoin : item?.placeHolder
                    cell?.changeColor(isHaveContent: viewModel?.legalCoin.count != 0 ? true : false)
                    break
                default:
                    break
                }
            }else {
                cell?.kindLabel.isHidden = false
                switch indexPath.row {
                case 0:
                    priceTextField = cell?.textField
                    cell?.textField.isUserInteractionEnabled = false
                    cell?.textField.text = viewModel?.priceStr
                    cell?.kindLabel.text = viewModel?.legalCoin
                    break
                case 1:
                    cell?.inforLabel.text = viewModel?.premium.count != 0 ? viewModel?.premium : kText("根据市场价的溢价比例")
                    cell?.changeColor(isHaveContent: viewModel?.premium.count != 0 ? true : false)
                    cell?.kindLabel.text = "%"
                    cell?.backArrorImage.isHidden = true
                    break
                case 1 + buyAddTag:
                    if !(viewModel?.isBuyBool)! {
                        lowerTextField = cell?.textField
                        cell?.textField.text = viewModel?.lowerPrice
                        cell?.kindLabel.text = viewModel?.legalCoin
                    }
                    break
                case 2 + buyAddTag:
                    smallAmount = cell?.textField
                    cell?.textField.text = viewModel?.smallAmount
                    cell?.kindLabel.text = viewModel?.legalCoin
                    break
                case 3 + buyAddTag:
                    bigAmount = cell?.textField
                    cell?.textField.text = viewModel?.bigAmount
                    cell?.kindLabel.text = viewModel?.legalCoin
                    break
                case 4 + buyAddTag:
                    cell?.inforLabel.text = viewModel?.paymentStyle.count != 0 ? viewModel?.paymentStyle :
                        kText("选择付款方式")
                    cell?.changeColor(isHaveContent: viewModel?.paymentStyle.count != 0 ? true : false)
                    cell?.kindLabel.text = ""
                    break
                default:
                    break
                }
            }
            
            return cell!
        case .cyMessageType?:
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? AdverContentCell
            if cell == nil {
                 cell = AdverContentCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.contentView.addSubview(textView)
                cell?.contentView.themeBackground = ThemeManager.ThemeColorKeys.background
                textView.themeTextColor = ThemeManager.ThemeColorKeys.text1
                textView.delegate = self
                textView.snp.makeConstraints { (make) in
                    make.left.equalToSuperview().offset(16)
                    make.width.equalTo(kSCREEN_WIDTH-32)
                    make.top.equalToSuperview().offset(10)
                    make.height.equalTo(170)
                }
                textView.addSubview(placeHolderLabel)
                textView.font = UIFont.systemFont(ofSize: 16)
                placeHolderLabel.font = UIFont.systemFont(ofSize: 12)
                textView.setValue(placeHolderLabel, forKey: "_placeholderLabel")
            }
            textView.text = viewModel?.message
            
            return cell!
        case .cyDefault? :
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? BaseTableViewCell
            if cell == nil {
                cell = BaseTableViewCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.selectionStyle = .none
                cell?.nameLabel.text = kText("高级设置 (选填)")
                cell?.nameLabel.font = UIFont.systemFont(ofSize: 12)
                cell?.nameLabel.changeLabelTextStyle(title: kText("(选填)"), color: UIColor(hexStr:"#c0c0c0"), font: UIFont.systemFont(ofSize: 12))
            }
            return cell!
            
        case .cyOpenTimeType?:
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? OpenTimeTableViewCell
            if cell == nil {
                cell = OpenTimeTableViewCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.selectionStyle = .none
                cell?.delegate = self
                cell?.changeStyle(defineBool: (viewModel?.definTimeBool)!)
            }
            return cell!
            
    
        case .cyAddTimeType? :
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? AddTimeCell
            if cell == nil {
                cell = AddTimeCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.delegate = self
            }
            return cell!

        case .cyShowTimeType? :
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? TimeTableViewCell
            if cell == nil {
                cell = TimeTableViewCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.contentView.themeBackground = ThemeManager.ThemeColorKeys.background3
                cell?.selectionStyle = .none
                cell?.delegate = self
            }
            cell?.index = indexPath.row
            cell?.dateLabel.text = viewModel?.timeArr[indexPath.row].dateStr
            cell?.timeLabel.text = viewModel?.timeArr[indexPath.row].timeStr
            return cell!

        case .cySwitchType? :
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? SwitchTableCell
            if cell == nil {
                cell = SwitchTableCell(style: .default, reuseIdentifier: cellIdentifier!)
                cell?.switBtn.addTarget(self, action: #selector(switBtnAction(sender:)), for: UIControlEvents.touchUpInside)
                cell?.selectionStyle = .none
            }
            cell?.switBtn.tag = indexPath.section * 10
            cell?.nameLabel.font = UIFont.systemFont(ofSize: 12)
            cell?.nameLabel.text = item?.name
            if ((viewModel?.definTimeBool)! && indexPath.section == 6) || (!(viewModel?.definTimeBool)! && indexPath.section == 5) {
                securitySwitch = cell?.switBtn
                cell?.switBtn.isOn = (viewModel?.securityBool)!
            }else {
                trustSwitch = cell?.switBtn
                cell?.switBtn.isOn = (viewModel?.trustBool)!
            }
            return cell!
         
            
        default:
            
            return BaseTableViewCell(style: .default, reuseIdentifier: cellIdentifier!)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 2 {
            return 177
        }
        if (viewModel?.definTimeBool)! && indexPath.section == 5 && indexPath.row != viewModel?.timeArr.count {
            return 80
        }
        return 48
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 || section == 3 {
            return 10
        }
        if (viewModel?.openSetBool)! && (viewModel?.definTimeBool)! && section == 5 {
            return 10
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if (viewModel?.openSetBool)! && (viewModel?.definTimeBool)! && section == 5 {
            return 10
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 10))
        view.themeBackground = ThemeManager.ThemeColorKeys.background3

        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 10))
        view.themeBackground = ThemeManager.ThemeColorKeys.background3
        
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.endEditing(true)
        tableView.deselectRow(at: indexPath, animated: false)
        if indexPath.section == 0  {
            if indexPath.row == 0 {
                self.endEditing(true)
                let selectPickerView = SlecterManager.manager.creatSlecterStyle(style: selectStyle.identiStyle, title: kText("选择币种"), selectStr: viewModel?.coninKid as AnyObject, dataArr: (viewModel?.coinNameArr)!, dataSource: self)
                selectPickerView.tag = indexPath.section*10 + 500
                selectPickerView.pickerShow()
            }
        }
        
        if indexPath.section == 0 && indexPath.row == 1 {
            let controller = CountrySelectedViewController()
            controller.isUnShowCord = true
            controller.delegate = self
            self.dataSource.controller?.navigationController?.pushViewController(controller, animated: true)
        }
        
        if indexPath.section == 0 && indexPath.row == 2 {
            let selectPickerView = SlecterManager.manager.creatSlecterStyle(style: selectStyle.identiStyle, title: kText("选择币种"), selectStr: viewModel?.legalCoin as AnyObject, dataArr: KLegalArr, dataSource: self)
            selectPickerView.tag =  502
            selectPickerView.pickerShow()
            
        }
        if indexPath.section == 1 && indexPath.row == 4 + buyAddTag{
            var payType = viewModel?.paymentStyle ?? ""
            payType = kText(payType)
            let selectPickerView = SlecterManager.manager.creatSlecterStyle(style: selectStyle.identiStyle, title: kText("付款方式"), selectStr: payType as AnyObject, dataArr: KPaymentStyleArr, dataSource: self)
            selectPickerView.tag = indexPath.section*10 + 500 + indexPath.row
            
            selectPickerView.pickerShow()
        }
        
        if indexPath.section == 1 && indexPath.row == 1 {
            let selectPickerView = SlecterManager.manager.creatSlecterStyle(style: selectStyle.identiStyle, title: kText("溢价比例"), selectStr: (viewModel?.premium.count != 0 ? viewModel?.premium : "0")as AnyObject, dataArr: KPremiumArr, dataSource: self)
            selectPickerView.tag = indexPath.section*10 + 500 + indexPath.row
            
            selectPickerView.pickerShow()
        }
        
        if indexPath.section == 3 && indexPath.row == 0 {
            viewModel?.openSetBool = !(viewModel?.openSetBool)!
            viewModel?.archiveCellKind()
            tableView.reloadData()
            if (viewModel?.openSetBool)! {
                let time: TimeInterval = 0.3
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    self.tableView.setContentOffset(CGPoint(x:0,y:self.tableView.contentOffset.y+144), animated: true)
                }
            }
        }
        
        if (viewModel?.definTimeBool)! && indexPath.section == 5 && indexPath.row != viewModel?.timeArr.count {
            self.goToTime(changeTimeBool: true, index: indexPath.row)
        }
    }
    
    
    //MARK DefinTimeDelegate
    
    func defineTime(definBool: Bool) {
        viewModel?.definTimeBool = definBool
        viewModel?.archiveCellKind()
        tableView.reloadData()
    }
    
    @objc func switBtnAction(sender:UISwitch) {
        if sender.isEqual(securitySwitch) {
            viewModel?.securityBool = sender.isOn
        }else {
            viewModel?.trustBool = sender.isOn
        }
    }
    

    func goToTime(changeTimeBool:Bool,index:Int)  {
        let contoller = SetOpenTimeViewController()
        if changeTimeBool {
            contoller.viewModel?.isUpdate = true
            contoller.viewModel?.model = (viewModel?.timeArr[index])!
        }
        contoller.block = { (model:TimeModel) in
            if !changeTimeBool {
                self.viewModel?.timeArr.append(model)
            }
            self.viewModel?.archiveCellKind()
            self.tableView.reloadData()
        }
        
        self.viewModel?.controller?.navigationController?.pushViewController(contoller, animated: true)
    }
    
    // MARK SlecterProcotol
    func selectData(selecter: AnyObject?) {
        let selecterStr = selecter as! String
        if SlecterManager.manager.selectPickerView?.tag == 500 {
            viewModel?.coninKid = selecterStr
            viewModel?.archiveCoinKind()
            tableView.reloadData()
        }else if SlecterManager.manager.selectPickerView?.tag == 502 {
            viewModel?.legalCoin = selecterStr
            viewModel?.archiveCoinPrice()
            tableView.reloadData()
            
        }else if SlecterManager.manager.selectPickerView?.tag == 514 + buyAddTag {
            viewModel?.paymentStyle = selecterStr
            let index:NSIndexPath = NSIndexPath(row: 4+buyAddTag, section: 1)
            self.tableView .reloadRows(at: [index as IndexPath], with: .fade)
        }else if SlecterManager.manager.selectPickerView?.tag == 511 {
            viewModel?.premium = selecterStr
            viewModel?.archiveCoinPrice()
            tableView.reloadData()
        }
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
           tableView.reloadData()
        }
        
    }
    
    
   
    deinit {
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "TiltleNotification"), object: nil)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

extension AdvertView:CountrySelectDelegate {
    func selectCountry(model: CountryModel) {
        viewModel?.countryStr = model.countryChineseName
        if AppCacheInfo.default.isEnlish {
            viewModel?.countryStr = model.countryEnglishName
        }
        let index:NSIndexPath = NSIndexPath(row: 1, section: 0)
        self.tableView .reloadRows(at: [index as IndexPath], with: .fade)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        
        return textField.cheakNumberFormat(digit: 8, range: range, string: string, interger: 8)
        
    }
    
    @objc func textFieldDidChangeValue(textField:UITextField) {
        if textField.isEqual(priceTextField) {
            viewModel?.priceStr = textField.text!
        }else if textField.isEqual(smallAmount) {
            viewModel?.smallAmount = textField.text!
        }else if textField.isEqual(bigAmount) {
            viewModel?.bigAmount = textField.text!
        }else if textField.isEqual(termTextField) {
            viewModel?.termStr = textField.text!
        }else if textField.isEqual(lowerTextField) {
            viewModel?.lowerPrice = textField.text!
        }
        
    }
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text.count == 0 {
            return true
        }
//        if text.containsEmoji {
//            return false
//        }
        
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        viewModel?.message = textView.text
    }
    
    
}

 extension AdvertView:TimeDelegate, AddTimeDelegate {
    func delegate(index: Int) {
        viewModel?.timeArr.remove(at: index)
        self.viewModel?.archiveCellKind()
        tableView.reloadData()
    }
    
    func addTime() {
        self.goToTime(changeTimeBool: false, index: 0)
    }
    
 }
